<template>
  <div class="edit-extra">
    <div class="item" v-for="(item, index) in list" :key="index">
      <div style="flex: 1">
        <el-input style="margin-bottom: 10px" v-model="item.name" type="text" placeholder="属性名"></el-input>
        <el-input v-model="item.value" type="text" placeholder="属性值"></el-input>
      </div>
      <el-button style="margin-left: 10px" type="danger" @click="del(index)">删除</el-button>
    </div>
    <el-button @click="add">新增</el-button>
  </div>
</template>

<script>
export default {
  name: 'EditExtra',
  props: {
    /* JSON字符串 */
    value: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      list: []
    };
  },
  watch: {
    value: {
      handler(val) {
        this.list = [];
        try {
            const list = []
            if(val) {
                const valJson = JSON.parse(val);
                for(let k in valJson) {
                    let obj = {};
                    obj.name = k;
                    obj.value = valJson[k];
                    list.push(obj);
                }
            }
            this.list = list;
        } catch (e) {
          console.log('JSON解析出错', e);
        }
      },
      immediate: true
    }
  },
  methods: {
    add() {
      this.list.push({
        name: '',
        value: ''
      });
    },
    del(index) {
      this.list.splice(index, 1);
    },
    save() {
      this.extraList = {};
      this.list.map((item) => {
        if (item.name && item.value) {
        //   this.extraList.push(item);
          this.extraList[item.name] = item.value;
        }
      });

      
      this.$emit('input', Object.keys(this.extraList).length ? JSON.stringify(this.extraList) : '');
    }
  }
};
</script>

<style scoped lang="scss">
.edit-extra {
  .item {
    display: flex;
    border-radius: 8px;
    border: 1px dashed #ccc;
    margin-bottom: 10px;
    padding: 10px;
  }
}
</style>